package nio.common;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;

public class Channel {
	public static void main(String[] args) {
		RandomAccessFile aFile;
		RandomAccessFile aFile2;
		try {
			aFile = new RandomAccessFile("C:\\Users\\Administrator\\Desktop\\nio.txt", "rw");
			aFile2 = new RandomAccessFile("C:\\Users\\Administrator\\Desktop\\nio2.txt", "rw");

			FileChannel fileChannel = aFile.getChannel();
			FileChannel fileChannel2 = aFile2.getChannel();
//			scatterAndGather(fileChannel);
			 commonTest(fileChannel);
			aFile.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void commonTest(FileChannel fileChannel) {
		try {
			// CharBuffer buf = CharBuffer.allocate(5);
			ByteBuffer buf = ByteBuffer.allocate(5);
			// buf.put((byte) 1);

			int bytesRead = fileChannel.read(buf);
			while (bytesRead != -1) {

				System.out.println("Read num:" + bytesRead);
				buf.flip();
//				buf.mark();
				while (buf.hasRemaining()) {
					// fileChannel.write(buf);//写往通道中一次直接读完了
					System.out.println((char) buf.get());// get出来一次只是读一个
					// break;
				}
//				buf.reset();// 不论在Mark和reset期间读了或者写了多少数据，reset回到Mark标识的位置
//				System.out.println((char) buf.get());
				// buf.clear();//开始符号设为0，下次向buf中写数据是从0开始写的
				buf.compact();// 开始符号也设为0，但是buf中还未读取的数据还在，下次向buf中写数据是从已有数据下一个位置开始写的

				bytesRead = fileChannel.read(buf);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void scatterAndGather(FileChannel fileChannel) {
		ByteBuffer header = ByteBuffer.allocate(5);
		ByteBuffer body = ByteBuffer.allocate(4);

		ByteBuffer[] bufferArray = { header, body };
		try {
			long key = fileChannel.read(bufferArray);
			System.out.println(key);
			header.flip();
				while (header.hasRemaining())
					System.out.println((char) header.get());
				System.out.println("==============");
				body.flip();
				while (body.hasRemaining())
					System.out.println((char) body.get());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
